package com.ts.common.security.hanlder;

import com.alibaba.fastjson.JSON;
import com.ts.common.security.annotation.LoginUser;
import com.ts.common.security.dto.UserToken;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

/**
 * 有@LoginUser注解的方法参数，注入当前登录用户
 */
public class LoginUserHandlerMethodArgumentResolver implements HandlerMethodArgumentResolver {

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        // 参数类型是UserEntity并且形参上加了@LoginUser注解，才能调用resolveArgument方法
        return parameter.getParameterType().isAssignableFrom(UserToken.class) && parameter.hasParameterAnnotation(LoginUser.class);
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer container,
                                  NativeWebRequest request, WebDataBinderFactory factory) throws Exception {

        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        String userInfo = requestAttributes.getRequest().getHeader("userInfo");

        UserToken userToken = JSON.parseObject(userInfo, UserToken.class);
        return userToken;
    }
}